package pri.damai.xiaowu.auth.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import pri.damai.xiaowu.common.core.vo.ResultVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 返回工具类
 * @Desc
 * @Author DaMai
 * @Date 2021/11/5 11:15
 * 但行好事，莫问前程。
 */
public class HttpUtil {

    /** Json 序列化 */
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 返回 Json 格式响应
     * @apiNote [附加描述]
     * @param response response
     * @param resultVO 返回体
     * @author DaMai
     * @date 2021/11/5 11:18
     */
    public static void respJson(HttpServletResponse response, ResultVO<?> resultVO) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter out = response.getWriter();
        // 处理返回值
        String s = OBJECT_MAPPER.writeValueAsString(resultVO);
        out.write(s);
        out.flush();
        out.close();
    }

    /**
     * 判断请求方法与请求头 Content-Type 类型
     * @apiNote [附加描述]
     * @param request request 请求
     * @author DaMai
     * @date 2021/11/5 11:25
     */
    public static void checkContentType(HttpServletRequest request, HttpMethod method, String... mediaTypes) {
        if (!Objects.equals(request.getMethod(), HttpMethod.POST.name())) {
            throw new AuthenticationServiceException(
                    "不支持的请求方法: " + request.getMethod());
        }

        Arrays.stream(mediaTypes)
                .filter(mediaType ->
                {
                    String contentType = request.getContentType();
                    return Objects.equals(request.getContentType(), mediaType);
                })
                .findAny()
                .orElseThrow(
                        () -> new AuthenticationServiceException(
                                "不支持的 Http content-type:" + request.getContentType()
                        )
                );
    }

    public static void main(String[] args) {
        Stream.of("a", "b", "c")
                .filter(mediaType -> Objects.equals("d", mediaType))
                .findAny()
                .orElseThrow(
                        () -> new AuthenticationServiceException(
                                "不支持的 Http content-type:"
                        )
                );

    }
}
